<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>06_列表渲染_过滤与排序</title>
</head>
<body>
<!--
1. 列表过滤
2. 列表排序
-->

<div id="demo">
    <input v-model="searchName"/><br/>
    <ul>
        <li v-for="(p,index) in filterPersons" :key="index">
            {{p.name}} --- {{p.age}}
        </li>
    </ul>
    <button @click="orderType=2">年龄升序</button>
    <button @click="orderType=1">年龄降序</button>
    <button @click="orderType=0">原本顺序</button>

</div>

<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
    /*persons: [
        {name: 'Tom', age: 18},
        {name: 'Jack', age: 17},
        {name: 'Bob', age: 19},
        {name: 'Mary', age: 16}
    ],*/
    new Vue({
        el: '#demo',
        data: {
            searchName: '',
            orderType: 0, // 0 原始，1 降序 ，2 升序
            // filterPersons: [],
            persons: [
                {name: 'Tom', age: 18},
                {name: 'Jack', age: 17},
                {name: 'Bob', age: 19},
                {name: 'Mary', age: 16}
            ]
        },
        computed: {
            // 监听这个的变化
            filterPersons() {
                const {searchName, orderType, persons} = this;
                let resultPersons = [...persons];
                // debugger
                if (searchName !== '') {
                    // 过滤
                    resultPersons = resultPersons.filter(p => p.name.indexOf(searchName) !== -1);
                }
                // 判断是否需要排序
                resultPersons = resultPersons.sort((p1, p2) => {
                    if (orderType === 0) {
                        return 0
                    } else if (orderType === 1) {
                        return p2.age - p1.age;
                    } else if (orderType === 2) {
                        return p1.age - p2.age;
                    }
                })
                // 返回结果
                return resultPersons;

            }
        }
    })
</script>
</body>
</html>